package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result orderByList() {
        //首先先从redis查询数据
        String  TypeJson= stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_TYPE_KEY);
        //判断是否为空
        if(!StringUtils.isEmpty(TypeJson)){
            List<ShopType> shopTypes = JSONUtil.toList(TypeJson, ShopType.class);
            //返回数据
            return Result.ok(shopTypes);
        }
        //从数据库进行查询
        LambdaQueryWrapper<ShopType> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(ShopType::getSort);
        List<ShopType> list = this.list(queryWrapper);
        if(list.isEmpty()){
            //查询数据为空，返回错误信息
            Result.fail("首页加载失败");
        }
        String jsonStr = JSONUtil.toJsonStr(list);
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_TYPE_KEY,jsonStr,RedisConstants.CACHE_SHOPTYPE_TTL, TimeUnit.MINUTES);
        //返回Json数据
        return Result.ok(jsonStr);

    }
}
